<template>
  <!-- 弹窗图片 -->
  <!-- 添加的图片 -->
  <div style="display: relative">
    <div class="dialog-title-yy-information">
      <img src="@/assets/img/module2/content.png" alt="弹窗图片" />
      <span class="dialog-title-text-yy-information">控制台</span>
    </div>

    <button @click="closeDialog" class="botton-shut-icon-yy-information"></button>

    <div class="dialog-container-yy-information">
      <div class="bottom-section-yy-information">
        <!-- 方案名称 -->
        <div style="margin-bottom: 3px; display: flex; align-items: center">
          <p class="up-content-text-yy-information" style="color: rgba(135, 183, 218, 1)">
            空域对象名称：
          </p>
          <div class="info-box-yy-information">
            <span class="info-box-text-yy-information">{{
              selectedObjectName
            }}</span>
          </div>
        </div>
        <!-- 创建时间 -->
        <div style="margin-bottom: 3px; display: flex; align-items: center">
          <p class="up-content-text-yy-information" style="color: rgba(135, 183, 218, 1)">
            空域开启/关闭：
          </p>
          <div class="info-box-yy-information">
            <select v-if="isEditing" v-model="tempSelectedDetails.startStopState" class="info-box-yy-information"
              style="color: white">
              <option value="开启" style="color: black">开启</option>
              <option value="关闭" style="color: black">关闭</option>
            </select>
            <span v-else class="info-box-text-yy-information">{{
              selectedDetails.startStopState
            }}</span>
          </div>
        </div>
        <div style="margin-bottom: 3px; display: flex; align-items: center">
          <p class="up-content-text-yy-information" style="color: rgba(135, 183, 218, 1)">
            时段开始：
          </p>
          <el-date-picker v-if="isEditing" v-model="tempSelectedDetails.startTime" value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime" placeholder="选择开始时间" style="margin-top: 5px;" class="el-date-picker-custom"
            :disabled="false">
          </el-date-picker>
          <el-date-picker v-else v-model="selectedDetails.startTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
            placeholder="选择开始时间" style="margin-top: 5px;" class="el-date-picker-custom" :disabled="true">
          </el-date-picker>
        </div>
        <div style="margin-bottom: 3px; display: flex; align-items: center">
          <p class="up-content-text-yy-information" style="color: rgba(135, 183, 218, 1)">
            时段结束：
          </p>
          <el-date-picker v-if="isEditing" v-model="tempSelectedDetails.endTime" value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime" placeholder="选择结束时间" style="margin-top: 5px;" class="el-date-picker-custom"
            :disabled="false">
          </el-date-picker>
          <el-date-picker v-else v-model="selectedDetails.endTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
            placeholder="选择结束时间" style="margin-top: 5px;" class="el-date-picker-custom" :disabled="true">
          </el-date-picker>
        </div>

        <div style="margin-bottom: 3px; display: flex; align-items: center">
          <p class="up-content-text-yy-information" style="color: rgba(135, 183, 218, 1)">
            容量阈值系数：
          </p>
          <div class="info-box-yy-information">
            <input v-if="isEditing" type="number" v-model="tempSelectedDetails.capacityThreshold"
              class="info-box-yy-information" style="color: white" />
            <span v-else class="info-box-text-yy-information">{{
              selectedDetails.capacityThreshold
            }}</span>
          </div>
        </div>

        <div style="margin-bottom: 3px; display: flex; align-items: center">
          <p class="up-content-text-yy-information" style="color: rgba(135, 183, 218, 1)">
            运行间隔系数：
          </p>
          <div class="info-box-yy-information">
            <input v-if="isEditing" type="number" v-model="tempSelectedDetails.safeIntervalThreshold"
              class="info-box-yy-information" style="color: white" />
            <span v-else class="info-box-text-yy-information">{{
              selectedDetails.safeIntervalThreshold
            }}</span>
          </div>
        </div>
        <div class="body-container">
          <div class="regional_table">
            <!-- el-table 表格 -->
            <el-table :data="tableDatayhr" style="width: 100%;" :max-height="400">
              <!-- 动态渲染列 -->
              <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop"
                :label="column.label" auto-width>
              </el-table-column>

              <!-- 操作栏 -->
              <el-table-column label="操作" auto-width>
                <template #default="scope">
                  <!-- 将 "查看" 修改为 "编辑" -->
                  <button @click="handleEdit(scope.row)" class="view-button">编辑</button>
                  <button @click="handleDelete(scope.row)" class="delete-button">删除</button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件
            <div class="pagenation">
              <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
              </el-pagination>
            </div> -->
          </div>
        </div>
        <!-- 修改下面div使得三个button水平排布 -->
        <div class="button-container">
          <button class="submit-button-yy-information" @click="addNewClick()">
            新增
          </button>
          <button class="submit-button-yy-information" @click="cancelClick()">
            取消
          </button>
          <button class="submit-button-yy-information" @click="saveClick()">
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import axios from "axios";
export default {
  name: "CustomDialogModule2PlanningScheme",

  data() {
    return {
      isEditing: false,
      selectedVenue: "",
      selectedLine: "",
      selectedRegion: "",
      tempSelectedDetails: {},
      // selectedDetails: {},
      tableColumns: [
        { prop: 'startTime', label: '时段开始', width: '25' },
        { prop: 'endTime', label: '时段结束', width: '25' },
        { prop: 'startStopState', label: '空域启停', width: '10' },
        { prop: 'capacityThreshold', label: '容量阈值系数', width: '10' },
        { prop: 'safeIntervalThreshold', label: '空域间隔系数', width: '10' }
      ],
      selectedDetails: {
        "startTime": "",
        "endTime": "",
        "startStopState": "",
      },
      tableDatayhr: []
    };
  },

  props: {
    // selectedDetails: {
    //   required: true,
    // },
    selectedObjectName: {
      required: true,
    },
    selectedObjectId: {
      required: true,
    },
    statusDialogVisible: {
      type: Boolean,
      required: true,
    }
    // visible: {
    //   type: Boolean,
    //   required: true,
    // },
  },
  watch: {
    // 监听 selectedObjectName 值的变化
    async selectedObjectName(newVal, oldVal) {
      console.log('selectedObjectName 变化了:', oldVal, '=>', newVal);
      // 你可以在这里处理值变化时的逻辑
      this.resetSelectedDetails();
      // 调用封装好的方法来更新表格
      await this.fetchHistoricalRecords();
    },
  },
  methods: {
    resetSelectedDetails() {
    this.selectedDetails = {
      "startTime": "",
      "endTime": "",
      "startStopState": "",
    };
    this.isEditing = false;
    this.tempSelectedDetails = {};
  },
    async handleDelete(row) {
      try {
        console.log("Deleting record:", row);
        // 确认用户是否真的要删除
        const confirmDelete = confirm("你确定要删除这个记录吗?");
        if (!confirmDelete) return;

        // 执行删除操作（例如调用 API）
        const response = await axios.post('http://47.99.75.194:8086/module6/delete', {
          operationId: row.operationId,
          objectId: this.selectedObjectId,
          airspaceObjectName: this.selectedObjectName
        });

        if (response.data.code === 0) {
          // 删除成功，重新加载数据
          await this.fetchHistoricalRecords();
        } else {
          console.error("删除失败:", response.data.message);
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    },
    async fetchHistoricalRecords() {
      try {
        const response = await axios.post('http://47.99.75.194:8086/module6/searchrecord', null, {
          params: {
            id: this.selectedObjectId,
            airspaceObjectName: this.selectedObjectName
          }
        });
        console.log("response", response);
        if (response.data.code === 0) {
          this.tableDatayhr = response.data.data;
          this.tableDatayhr.forEach((item) => {
            const regex = /\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*/;
            const matches = item.correspondingTimePeriod.match(regex);
            if (matches) {
              item.startTime = matches[1];
              item.endTime = matches[2];
            }
          });
          console.log("tableDatayhr", this.tableDatayhr);
        } else {
          this.tableDatayhr = [];
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    },
    handleEdit(row) {
      // 点击编辑时，将当前选择的操作记录放到 selectedDetails 并更新 tempSelectedDetails
      const airspaceObjectName = this.selectedDetails.airspaceObjectName;
      console.log("row", row)
      console.log("select...:", this.selectedDetails)
      const startStopState = row.startStopState;
      this.selectedDetails = JSON.parse(JSON.stringify(row));
      this.tempSelectedDetails = JSON.parse(JSON.stringify(row));
      this.tempSelectedDetails.airspaceObjectName = airspaceObjectName;
      this.selectedDetails.airspaceObjectName = airspaceObjectName;
      this.tempSelectedDetails.startStopState = startStopState;
      this.selectedDetails.startStopState = startStopState;
      console.log("tempSelect", this.tempSelectedDetails)
      this.isEditing = true; // 切换为编辑模式
      console.log("Selected record for editing:", this.selectedDetails);
    },
    addNewClick() {
      // 新增空白记录，进入编辑状态
      this.tempSelectedDetails = {
        id: null,
        objid: 1, // 默认 objid
        startTime: '',
        endTime: '',
        startStopState: '',
        capacityThreshold: '',
        safeIntervalThreshold: ''
      };
      this.isEditing = true; // 进入编辑模式
      console.log("Adding new record:", this.tempSelectedDetails);
    },
    cancelClick() {
      this.isEditing = false; // 退出编辑模式
    },
    closeDialog() {
      this.resetSelectedDetails();
      this.cancelClick();
      this.$emit("update:statusDialogVisible", false); // 通知父组件关闭弹窗
    },
    getStatusPercentage(status) {
      switch (status) {
        case "未提交":
          return 0;
        case "已提交":
          return 25;
        case "审核中":
          return 75;
        case "审核完成":
          return 100;
        default:
          return 0;
      }
    },
    submitClick() {
      this.$emit("submitClickTransfer");
    },
    async saveClick() {
      this.isEditing = false; // 退出编辑模式
      // 将tempSelectedDetails的数据同步到selectedDetails
      this.selectedDetails = JSON.parse(JSON.stringify(this.tempSelectedDetails));
      console.log("mount selectDetails: ", this.selectedDetails);
      console.log("mount tempSelectDetails: ", this.tempSelectedDetails);
      console.log({
        id: this.selectedDetails.id,
        tablename: this.selectedDetails.airspaceObjectName,
        startstopstate: this.selectedDetails.startStopState,
        correspondingtimeperiod: this.selectedDetails.startTime + "-" + this.selectedDetails.endTime,
        capacitythreshold: this.selectedDetails.monitoringCapacity,
        safeintervalthreshold: this.selectedDetails.capacityThreshold
      })
      // 调用后端接口保存数据
      const response = await axios.post('http://47.99.75.194:8086/module6/saveorinsert', {
        objectId: this.selectedObjectId,
        airspaceObjectName: this.selectedObjectName,
        operationId: this.selectedDetails.operationId,
        startStopState: this.selectedDetails.startStopState,
        correspondingTimePeriod: this.selectedDetails.startTime + "-" + this.selectedDetails.endTime,
        capacityThreshold: this.selectedDetails.capacityThreshold,
        safeIntervalThreshold: this.selectedDetails.safeIntervalThreshold
      })
      if (response.data.code === 0) {
        this.$message({
          message: '保存成功',
          type: 'success'
        });
      } else {
        this.$message({
          message: '保存失败',
          type: 'error'
        });
      }
      await this.fetchHistoricalRecords();
    },
    sendClick() {
      // 发送相关逻辑
    }
  },
  // 组件加载的时候同步selectedDetails到tempSelectedDetails
  mounted() {
    this.tempSelectedDetails = JSON.parse(JSON.stringify(this.selectedDetails));
    console.log("mount selectDetails: ", this.selectedDetails);
    console.log("mount tempSelectDetails: ", this.tempSelectedDetails);
  },
};
</script>





<style scoped>
.botton-shut-icon-yy-information {
  background-image: url("@/assets/img/nav/关闭.png");
  position: absolute;
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  right: 30px;
  top: 0;
  width: 40px;
  height: 40px;
  z-index: 3;
  border: none;
  cursor: pointer;
  /* filter: brightness(0.1); */
}

.dialog-title-yy-information {
  width: 90%;
  position: inherit;
  top: 5%;
  left: 5%;
  /* background-color: white; */
}

.dialog-title-text-yy-information {
  position: absolute;
  left: 13%;
  overflow-wrap: break-word;

  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 23px;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.dialog-container-yy-information {
  background-image: url("@/assets/img/module2/bg.png");
  background-size: 100% 100%;
  /* background-color:white; */
  padding: 0px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  position: relative;
  top: 10%;
  left: 0%;
  padding: 0px;
  flex-grow: 1;
}

.top-section-yy-information {
  /* z-index: 10; */
  /* position:absolute; */
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 5%;
  margin-top: 5%;
  left: 0%;
  height: 8%;
  top: 5%;
  /* display: block; */
  /* background-color:white; */
}

.progress-labels-yy-information {
  position: absolute;
  color: white;
  top: 7%;
  left: 50%;
  transform: translate(-50%);
  font-size: 20px;
}

.bottom-section-yy-information {
  position: inherit;
  display: inline;
  /* background-color: white; */
  left: 0%;
  top: 0px;
  width: 100%;
  height: 85%;
  padding: 5% 0px;
  /* margin-left: 15px;
  flex-grow: 1; */
}

.select-section-yy-information {
  background-image: url("@/assets/img/module2/bg.png");
  background-size: 100% 100%;
  position: absolute;
  /* background-color: white; */
  left: 3%;
  top: 30%;
  width: 94%;
  height: 53%;
}

.select-section-title-yy-information {
  background-image: url("@/assets/img/module2/selecttitle.png");
  /* background-color: #fff; */
  background-size: 100% 100%;
  position: absolute;
  /* background-color: white; */
  left: 9%;
  top: 9%;
  width: 84%;
  height: 16%;
}

.select-section-titletext-yy-information {
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  font-weight: 600;
}

.dropdown-container-yy-information {
  /* background-color: white; */
  position: absolute;
  top: 25%;
  left: 0%;
  height: 75%;
  width: 100%;
}

.dropdown-yy-information {
  position: relative;
  left: 15%;
  width: 70%;
  height: 20%;
  margin-top: 5%;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ccc;
  color: white;
  font-weight: 600;
  background-color: black;
  font-size: 20px;
}

.dropdown-yy-information option {
  background-color: #2b2b2b;
  /* 设置下拉选项的背景颜色 */
  color: #fff;
  /* 设置下拉选项的文字颜色 */
}

.button-container {
  margin-top: 5%;
  padding: 0 10%;
  display: flex;
  justify-content: space-between;
  /* Adjust the space between buttons */
}

.submit-button-yy-information {
  background-image: url("@/assets/img/module2/buttonblue.png");
  position: relative;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  bottom: 4%;
  height: 46px;
  width: 100px;
  border: none;
  cursor: pointer;
  color: white;
  font-size: 20px;
  text-align: center;
}

.up-content-text-yy-information {
  margin-right: 3%;
  text-align: right;
  width: 35%;
}

.info-box-yy-information {
  position: relative;
  background-image: url("@/assets/img/module2/text.png");
  background-size: cover;
  background-color: transparent;
  padding: 0px;
  width: 200px;
  min-height: 40px;
  height: 100%;
  display: flex;
  /* justify-content: center; 水平居中 */
  align-items: center;
}

.info-box-text-yy-information {
  margin-left: 10px;
  font-size: 14px;
  color: rgba(208, 219, 227, 1);
  /* position: absolute; */
  width: 80%;
  /* top: 50%; */
  /* justify-content: center; 水平居中 */
  /* left: 50%; */
  /* transform: translate(-50%, -50%); */
}

.el-date-picker-custom {
  /* width: 100% !important; */
  width: 200px !important;
  background-color: transparent;
}

.el-date-picker-custom /deep/ .el-input__inner {
  background-color: transparent !important;
  color: white;
}

.body-container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  width: 99%;
  padding: 1vh 1vw 1vh 0;
  max-height: 300px;
}

.regional_table {
  overflow-y: auto;
  /* 超出时垂直滚动 */
  height: 70vh;

}

/* 最外层透明表格背景与白色字体 */
.regional_table /deep/ .el-table,
.regional_table /deep/ .el-table__expanded-cell {
  background-color: transparent;
  /* 设置透明背景 */
  color: white;
  /* 表格文字颜色 */
}

/* 针对 el-table 隐藏滚动条 */
.el-table__body-wrapper::-webkit-scrollbar {
  width: 0;
  height: 0;
}

.regional_table /deep/ .el-table__body-wrapper {
  scrollbar-width: none;
  /* Firefox 隐藏滚动条 */
  -ms-overflow-style: none;
  /* IE/Edge 隐藏滚动条 */
}

/* 表格头部和单元格的背景颜色透明 */
.regional_table /deep/ .el-table th,
.regional_table /deep/ .el-table tr,
.regional_table /deep/ .el-table td {
  background-color: transparent !important;
  /* 背景透明 */
  color: rgb(183, 179, 179);
  /* 确保文字为白色 */
}

/* 设置表格边框 */
.regional_table /deep/ .el-table__body-wrapper {
  border: 0.5px solid transparent;
  /* 边框为白色 */
}

/* 如果表头或其他部分需要特殊透明处理 */
.regional_table /deep/ .el-table__header-wrapper {
  background-color: rgba(255, 255, 255, 0.1);
  /* 表头轻微透明 */
}

.regional_table /deep/ .el-table .el-table__cell {
  padding: 0.5rem;
}


/* pagenation */
.pagenation {
  height: 10%;
  margin-top: 1rem;
  float: right;
}

.regional_table /deep/ .el-pagination.is-background .el-pager li {
  background: transparent;
  color: #a09292;
}

.regional_table /deep/ .el-pagination.is-background .btn-prev {
  background: transparent;
}

.regional_table /deep/ .el-input__inner {
  background-color: transparent;
  color: #fff;
}
</style>